﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class BuildUI : MonoBehaviour
{
    public bool bCollObj;

    List<GameObject> m_AmmoLine;

    GameObject BuildingPrefab; //건설되는 애
    //float fRotSpeed ;
    public bool bStructObject; // If this true, Struct Object!

    public bool bOriginal = false; // it isnt Dragging Instantiate;
    public Vector3 vOriginalPos;
    public int iDragIndex;
    int iCoverDragNum; // when Drag distance is longer than colliderX size, ++ this;
    float fDragTimer; //Immedietly Struct Timer;

    public int m_iOriginalIdx;
    public int m_iTileIdx;

    public bool m_bUITile; //빌드건물 타일 몇곱하기몇 알려주는거 사이즈
    public int m_iUITileIdx; //BuildUITile Idx;

    List<int> m_ListBuildQueuedIdx;
    public TILE_OPTION m_PrevOption;

    // Use this for initialization
    void Start()
    {
        m_AmmoLine = new List<GameObject>();

        transform.localScale = new Vector3(1, 1, 0);
        //transform.localScale = new Vector3(525, 525, 0);
        //GetComponent<BoxCollider2D>().size = GetComponent<BuildStatus>().m_BuildData.vSize;

        GetComponent<SpriteRenderer>().color = new Color(130 / 255f, 200 / 255f, 110 / 255f, 150 / 255f);
        bCollObj = false;

        if (!m_bUITile)
        {
            GameObject.Find("Price(Clone)").GetComponent<BuildUI_Price>().iPriceToPay = GetComponent<BuildStatus>().m_BuildData.iPrice;
            GameObject.Find("Price(Clone)").GetComponent<BuildUI_Price>().iPrice = GetComponent<BuildStatus>().m_BuildData.iPrice;

            if (GetComponent<BuildStatus>().m_BuildData.enType != BUILD_TYPE.COVER)
            {
                List<int> tmpTileList = Calculate.GetSizeTileInHere(Calculate.GetMyTileIdx(transform.position), GetComponent<BuildStatus>().m_BuildData.vSize);

                for (int i = 0; i < tmpTileList.Count; ++i)
                {
                    GameObject tmpObj = Instantiate(Resources.Load("Prefaps/UI/StaticUI/BuildUI/BuildUITile") as GameObject) as GameObject;
                    tmpObj.transform.parent = transform.parent;
                    tmpObj.GetComponent<BuildUI>().m_iUITileIdx = tmpTileList[i] - Calculate.GetMyTileIdx(transform.position);
                    tmpObj.GetComponent<BuildUI>().m_bUITile = true;
                }
            }
        }
        iCoverDragNum = 0;
        fDragTimer = 0;

        m_ListBuildQueuedIdx = new List<int>();

        if (!m_bUITile)
        {
            float fAngle = Calculate.GetAngle(Calculate.GetMousePos(), vOriginalPos);
            if (fAngle <= -135.0f || fAngle > 135.0f)
                transform.position = Calculate.FindThisTile(m_iOriginalIdx - (iDragIndex + 1)).transform.position;
            else if (fAngle >= -135.0f && fAngle < -45.0f)
                transform.position = Calculate.FindThisTile(m_iOriginalIdx + (iDragIndex + 1) * GameObject.Find("DebugTile").GetComponent<Background>().m_iTileCountX).transform.position;
            else if (fAngle >= -45 && fAngle < 45.0f)
                transform.position = Calculate.FindThisTile(m_iOriginalIdx + (iDragIndex + 1)).transform.position;
            else if (fAngle >= 45 && fAngle < 135.0f)
                transform.position = Calculate.FindThisTile(m_iOriginalIdx - (iDragIndex + 1) * GameObject.Find("DebugTile").GetComponent<Background>().m_iTileCountX).transform.position;

            m_iTileIdx = Calculate.GetMyTileIdx(transform.position);
        }
        

    }

    public void AmmoSupplyDrawLine()
    {
        for (int j = 0; j < m_AmmoLine.Count; ++j)
        {
            if (m_AmmoLine[j])
                GameObject.Destroy(m_AmmoLine[j]);
        }

        for (int i = 0; i < GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().UnitList.Count; ++i)
        {
            if (Vector3.Distance(transform.position, GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().UnitList[i].gameObject.transform.position) < 1.0f)
            {
                m_AmmoLine.Add(GameObject.Instantiate(ResourceMgr.GetInstance().m_pMoveLine, transform.position, Quaternion.identity) as GameObject);
                m_AmmoLine[m_AmmoLine.Count - 1].GetComponent<Line>().SetLine(transform.position, GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().UnitList[i].gameObject.transform.position);
                m_AmmoLine[m_AmmoLine.Count - 1].GetComponent<Line>().m_pOwner = gameObject;
            }
        }
    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetKey(KeyCode.Escape))
        {
            Destroy(gameObject);
            Destroy(GameObject.Find("Price(Clone)").gameObject);
        }



        if (m_bUITile && !Input.GetMouseButton(0))
            GridMovement();

        if (bOriginal)
        {   
            if(GetComponent<BuildStatus>().m_BuildData.enType == BUILD_TYPE.COVER)
                WallDirectioning();
            BuildingUnablecheck();

            if (GameObject.Find("BuildUI").transform.GetChild(0).GetComponent<BuildStatus>().m_BuildData.strName == "Ammo Depot")
            {
                //AmmoSupplyDrawLine();
                m_AmmoLine = ResourceMgr.GetInstance().DrawBoundaryUnitLine(gameObject, m_AmmoLine, 1.0f, new Color(112 / 255f, 117 / 255f, 99 / 255f));
            }

            //if (Input.GetMouseButtonDown(0) && GetComponent<BuildStatus>().m_BuildData.enType == BUILD_TYPE.COVER)
            //{
            //    if (GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[Calculate.GetMyTileIdx(Calculate.GetMousePos())].GetComponent<Tile>().m_iOption == (int)TILE_OPTION.NORMAL)
            //    {
            //        GameObject NewBlock = Instantiate(gameObject) as GameObject;
            //        NewBlock.transform.parent = transform.parent;
            //        NewBlock.transform.position = GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[m_iTileIdx].transform.position;
            //        NewBlock.GetComponent<BuildUI>().bOriginal = false;
            //        NewBlock.GetComponent<BuildUI>().bStructObject = false;
            //        GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[Calculate.GetMyTileIdx(Calculate.GetMousePos())].GetComponent<Tile>().m_iOption = (int)TILE_OPTION.BUILD_QUEUED;
            //    }                

            //}else 
            if (Input.GetMouseButtonDown(0))
                vOriginalPos = Calculate.GetMousePos();

            if (Input.GetMouseButton(0))
            {// Drag!

                if (GetComponent<BuildStatus>().m_BuildData.enType == BUILD_TYPE.COVER)
                    DragObject();
                else
                {

                    fDragTimer += Time.deltaTime;

                    if (fDragTimer > 0.2f)
                    {
                        if (GetComponent<BuildStatus>().m_BuildData.strSpriteName == "MiniLight")
                            RotationCover();
                    }
                }
            }
            else if (Input.GetMouseButtonUp(0))
            {
                bool bTemp = false;
                for (int i = 0; i < transform.parent.childCount; ++i)
                {
                    if (bTemp = transform.parent.GetChild(i).GetComponent<BuildUI>().bCollObj) // bTemp -> false = struct!
                    {
                        bTemp = true;
                        break;
                    }
                }
                if (!bTemp)
                { // Struct
                    for (int i = 0; i < transform.parent.childCount; ++i)
                    {
                        transform.parent.GetChild(i).GetComponent<BuildUI>().bStructObject = true;
                    }
                    GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().g_iMoney -= GameObject.Find("Price(Clone)").GetComponent<BuildUI_Price>().iPriceToPay;
                    for (int j = 0; j < m_AmmoLine.Count; ++j)
                    {
                        if (m_AmmoLine[j])
                            GameObject.Destroy(m_AmmoLine[j]);
                    }
                    if (GetComponent<BuildStatus>().m_BuildData.enType == BUILD_TYPE.BUILDING)
                        Destroy(GameObject.Find("Price(Clone)").gameObject);

                }
                else
                { // Can't struct cause obstacle
                    if (GetComponent<BuildStatus>().m_BuildData.enType != BUILD_TYPE.BUILDING)
                    {
                        for (int i = 1; i < transform.parent.childCount; ++i)
                        {
                            transform.parent.GetChild(i).GetComponent<BuildUI>().DestroyThis();
                        }
                    }

                    bCollObj = false;
                    fDragTimer = 0;
                    iCoverDragNum = 0;
                    //GetComponent<SpriteRenderer>().color = new Color(130 / 255f, 200 / 255f, 110 / 255f, 150 / 255f);
                }
            }
            else if(!bStructObject)
                GridMovement();


        }
        else
        {
            if (!m_bUITile)
            {
                float fAngle = Calculate.GetAngle(Calculate.GetMousePos(), vOriginalPos);
                if (fAngle <= -135.0f || fAngle > 135.0f)
                    transform.position = Calculate.FindThisTile(m_iOriginalIdx - (iDragIndex + 1)).transform.position;
                else if (fAngle >= -135.0f && fAngle < -45.0f)
                    transform.position = Calculate.FindThisTile(m_iOriginalIdx + (iDragIndex + 1) * GameObject.Find("DebugTile").GetComponent<Background>().m_iTileCountX).transform.position;
                else if (fAngle >= -45 && fAngle < 45.0f)
                    transform.position = Calculate.FindThisTile(m_iOriginalIdx + (iDragIndex + 1)).transform.position;
                else if (fAngle >= 45 && fAngle < 135.0f)
                    transform.position = Calculate.FindThisTile(m_iOriginalIdx - (iDragIndex + 1) * GameObject.Find("DebugTile").GetComponent<Background>().m_iTileCountX).transform.position;

                m_iTileIdx = Calculate.GetMyTileIdx(transform.position);
                m_PrevOption = Calculate.GetMyTileOption(Calculate.GetMyTileIdx(transform.position));
            }
        }

        if (GetComponent<BuildStatus>())
        {
            if (GetComponent<BuildStatus>().m_BuildData.enType == BUILD_TYPE.COVER && (Input.GetMouseButton(0) || Input.GetMouseButtonUp(0)))
            {
                WallDirectioning();
            }
        }
        

        if (bStructObject && (!bOriginal || GetComponent<BuildStatus>().m_BuildData.enType == BUILD_TYPE.BUILDING) && !m_bUITile)
            StructObject();
        else if (bStructObject && bOriginal)
        {
            bStructObject = false;
            //GameObject NewBlock = Instantiate(gameObject) as GameObject;
            //NewBlock.transform.parent = transform.parent;
            //NewBlock.transform.position = GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[m_iTileIdx].transform.position;
            //NewBlock.GetComponent<BuildUI>().bOriginal = false;
            //NewBlock.GetComponent<BuildUI>().bStructObject = true;
            //GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[m_iTileIdx].GetComponent<Tile>().m_iOption = (int)TILE_OPTION.BUILD_QUEUED;
            //StructObject();

            GameObject NewBlock1 = Instantiate(gameObject) as GameObject;
            NewBlock1.transform.parent = transform.parent;
            NewBlock1.transform.position = Calculate.GetMousePos();
            NewBlock1.GetComponent<BuildUI>().bOriginal = true;
            NewBlock1.GetComponent<BuildUI>().bStructObject = false;
            NewBlock1.GetComponent<BuildUI>().enabled = true;
            StructObject();
        }

        if (Input.GetMouseButtonDown(1))
        {// Cancle!
            Destroy(gameObject);
            Destroy(GameObject.Find("Price(Clone)").gameObject);
            GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[Calculate.GetMyTileIdx(transform.position)].GetComponent<Tile>().m_iOption = (int)m_PrevOption;

            for (int j = 0; j < m_AmmoLine.Count; ++j)
            {
                if (m_AmmoLine[j])
                    GameObject.Destroy(m_AmmoLine[j]);
            }
        }
    }

    void GridMovement()
    {
        int tempIdx = Calculate.GetMyTileIdx(Calculate.GetMousePos()) + m_iUITileIdx;
        transform.position = GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[tempIdx].transform.position;
        m_iTileIdx = tempIdx;
    }

    void BuildingUnablecheck()
    {
        if (m_bUITile)
        {
            if (GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[Calculate.GetMyTileIdx(transform.position) + m_iUITileIdx].GetComponent<Tile>().m_iOption == (int)TILE_OPTION.BLOCK ||
                GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[Calculate.GetMyTileIdx(transform.position) + m_iUITileIdx].GetComponent<Tile>().m_iOption == (int)TILE_OPTION.BUILD
                || GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[Calculate.GetMyTileIdx(transform.position) + m_iUITileIdx].GetComponent<Tile>().m_iOption == (int)TILE_OPTION.BUILD_QUEUED)
            {
                bCollObj = true;
                GetComponent<SpriteRenderer>().color = new Color(200 / 255f, 110 / 255f, 110 / 255f, 150 / 255f);
            }
            else
            {
                bCollObj = false;
                GetComponent<SpriteRenderer>().color = new Color(130 / 255f, 200 / 255f, 110 / 255f, 150 / 255f);
            }
        }
        else if (GetComponent<BuildStatus>().m_BuildData.enType == BUILD_TYPE.BUILDING)
        {
            for (int i = 1; i < transform.parent.childCount; ++i)
            {
                bCollObj = false;
                GetComponent<SpriteRenderer>().color = new Color(130 / 255f, 200 / 255f, 110 / 255f, 150 / 255f);

                if (transform.parent.GetChild(i).GetComponent<BuildUI>().bCollObj)
                {
                    bCollObj = true;
                    GetComponent<SpriteRenderer>().color = new Color(200 / 255f, 110 / 255f, 110 / 255f, 150 / 255f);
                    break;
                }
            }
        }

        if (GetComponent<BuildStatus>())
        {
            bool bTmpCol = false;
            int iColObjIdx = 0;

            for (int i = 0; i < transform.parent.childCount; ++i)
            {
                if (Calculate.GetMyTileOption(Calculate.GetMyTileIdx(transform.parent.GetChild(i).transform.position)) != TILE_OPTION.NORMAL)
                {
                    bTmpCol = true;
                    iColObjIdx = i;
                    break;
                }
            }

            if (bTmpCol)
            {
                for (int i = iColObjIdx; i < transform.parent.childCount; ++i)
                {
                    transform.parent.GetChild(i).GetComponent<BuildUI>().bCollObj = true;
                    transform.parent.GetChild(i).GetComponent<SpriteRenderer>().color = new Color(200 / 255f, 110 / 255f, 110 / 255f, 150 / 255f);
                }
            }
            else
            {
                for (int i = 0; i < transform.parent.childCount; ++i)
                {
                    transform.parent.GetChild(i).GetComponent<BuildUI>().bCollObj = false;
                    transform.parent.GetChild(i).GetComponent<SpriteRenderer>().color = new Color(130 / 255f, 200 / 255f, 110 / 255f, 150 / 255f);
                }
            }

            //if (GetComponent<BuildStatus>().m_BuildData.enType == BUILD_TYPE.COVER)
            //{
            //    if (GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[Calculate.GetMyTileIdx(transform.position) + m_iUITileIdx].GetComponent<Tile>().m_iOption == (int)TILE_OPTION.BLOCK ||
            //    GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[Calculate.GetMyTileIdx(transform.position) + m_iUITileIdx].GetComponent<Tile>().m_iOption == (int)TILE_OPTION.BUILD)
            //    {
            //        bCollObj = true;
            //        GetComponent<SpriteRenderer>().color = new Color(200 / 255f, 110 / 255f, 110 / 255f, 150 / 255f);
            //    }
            //    else
            //    {
            //        bCollObj = false;
            //        GetComponent<SpriteRenderer>().color = new Color(130 / 255f, 200 / 255f, 110 / 255f, 150 / 255f);
            //    }
            //}
        }

    }


    void DragObject()
    {
        if(GetComponent<BuildStatus>().m_BuildData.strSpriteName == "MiniLight")
            RotationCover ();

        if (GetComponent<BuildStatus>().m_BuildData.enType == BUILD_TYPE.COVER)
        { // If this is cover, Drag can struct more;
            //정재순이 상수박으랫음 타일싸이즈 0.15 내탓아님

            int iDistancePerSize = (int)(Vector3.Distance(Calculate.GetMousePos(), vOriginalPos) / 0.15f);

            if (iDistancePerSize > iCoverDragNum)
            {
                if (GetComponent<BuildStatus>().m_BuildData.iPrice * (GameObject.Find("BuildUI").transform.childCount + 1)
                <= GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().g_iMoney)
                {
                    (Instantiate(gameObject) as GameObject).transform.parent = transform.parent;
                    GameObject.Find("BuildUI").transform.GetChild(GameObject.Find("BuildUI").transform.childCount - 1).GetComponent<BuildUI>().bOriginal = false;
                    GameObject.Find("BuildUI").transform.GetChild(GameObject.Find("BuildUI").transform.childCount - 1).GetComponent<BuildUI>().m_iOriginalIdx = m_iTileIdx;
                    GameObject.Find("BuildUI").transform.GetChild(GameObject.Find("BuildUI").transform.childCount - 1).GetComponent<BuildUI>().iDragIndex = iCoverDragNum;
                    ++iCoverDragNum;
                }

            }
            else if (iCoverDragNum > 0 && iCoverDragNum > iDistancePerSize)
            {
                Destroy(transform.parent.GetChild(transform.parent.childCount - 1).gameObject);
                //transform.parent.GetChild(transform.parent.childCount - 1).GetComponent<BuildUI>().DestroyThis();
                --iCoverDragNum;
            }

            //GameObject NewBlock = Instantiate(gameObject) as GameObject;
            //NewBlock.transform.parent = transform.parent;
            //m_iTileIdx = Calculate.GetMyTileIdx(Calculate.GetMousePos());
            //NewBlock.transform.position = GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[m_iTileIdx].transform.position;
            //NewBlock.GetComponent<BuildUI>().bOriginal = false;
            //NewBlock.GetComponent<BuildUI>().bStructObject = false;
            //GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[Calculate.GetMyTileIdx(Calculate.GetMousePos())].GetComponent<Tile>().m_iOption = (int)TILE_OPTION.BUILD_QUEUED;



        }

    }


    void WallDirectioning()
    {
        for (int i = 0; i < 4; ++i)
        {
            GetComponent<WallDirection>().m_bDirection[i] = false;
        }
        GetComponent<WallDirection>().m_iTileIdx = m_iTileIdx;
        GetComponent<WallDirection>().SurroundChecker();
    }

    void StructObject()
    {
        if (!bCollObj)
        {
            Destroy(gameObject);

            GameObject NewObject = null;

            switch (GetComponent<BuildStatus>().m_BuildData.enType)
            {
                case BUILD_TYPE.COVER:
                    BuildingPrefab = Resources.Load(string.Format("Prefaps/Cover/{0}", GetComponent<BuildStatus>().m_BuildData.strSpriteName)) as GameObject;

                    NewObject = Instantiate(BuildingPrefab, transform.position, transform.rotation) as GameObject;
                    NewObject.transform.parent = GameObject.Find("Cover").transform;
                    NewObject.GetComponent<BuildStatus>().m_BuildData = GetComponent<BuildStatus>().m_BuildData;
                    NewObject.GetComponent<Build>().m_iListTileIdx = Calculate.GetSizeTileInHere(Calculate.GetMyTileIdx(transform.position), GetComponent<BuildStatus>().m_BuildData.vSize);

                    GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().StructQueue.Add(NewObject.gameObject);
                    Calculate.ChangeTileOptionInSize(Calculate.GetMyTileIdx(transform.position), GetComponent<BuildStatus>().m_BuildData.vSize, TILE_OPTION.BUILD_QUEUED);
                    NewObject.GetComponent<WallDirection>().m_iTileIdx = m_iTileIdx;
                    break;

                case BUILD_TYPE.BUILDING:
                    BuildingPrefab = Resources.Load(string.Format("Prefaps/Cover/{0}", GetComponent<BuildStatus>().m_BuildData.strSpriteName)) as GameObject;

                    NewObject = Instantiate(BuildingPrefab, transform.position, transform.rotation) as GameObject;
                    NewObject.transform.parent = GameObject.Find("Tactic").transform;
                    NewObject.GetComponent<BuildStatus>().m_BuildData = GetComponent<BuildStatus>().m_BuildData;
                    NewObject.GetComponent<Build>().m_iListTileIdx = Calculate.GetSizeTileInHere(Calculate.GetMyTileIdx(transform.position), GetComponent<BuildStatus>().m_BuildData.vSize);

                    GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().StructQueue.Add(NewObject.gameObject);

                    List<int> tmpList = Calculate.GetSizeTileInHere(Calculate.GetMyTileIdx(transform.position), GetComponent<BuildStatus>().m_BuildData.vSize);
                    for (int i = 0; i < tmpList.Count; ++i)
                    {
                        GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[tmpList[i]].GetComponent<Tile>().m_iOption = (int)TILE_OPTION.BUILD_QUEUED;
                        Destroy(transform.parent.GetChild(i + 1).gameObject);
                    }
                    break;
            }



            //			GameObject Engineer = GameObject.Find("Engineers");
            //			
            //			for(int i = 0 ; i < Engineer.transform.childCount; ++i)
            //			{
            //				if(!Engineer.transform.GetChild(i).GetComponent<Engineer>().bWorking)
            //				{
            //					if(fEngineerDist > Vector3.Distance(transform.position, Engineer.transform.GetChild(i).transform.localPosition) || iNearestEngineerIndex == 99)
            //					{
            //						fEngineerDist = Vector3.Distance(transform.position, Engineer.transform.GetChild(i).transform.localPosition);
            //						iNearestEngineerIndex = i;
            //						
            //					}
            //				}
            //			}
            //			
            //			Engineer.transform.GetChild(iNearestEngineerIndex).GetComponent<UnitScript>().m_vecDest = new Vector2(transform.position.x, transform.position.y - 0.01f);
            //			Engineer.transform.GetChild(iNearestEngineerIndex).GetComponent<StateMachine>().SetState(new MoveState());
            //			Engineer.transform.GetChild(iNearestEngineerIndex).GetComponent<Engineer>().bWorking = true;
            //			iNearestEngineerIndex = 99;
        }
    }

    void RotationCover()
    {
        Vector2 vLook = gameObject.transform.position - Camera.main.ScreenToWorldPoint(Input.mousePosition);

        float angle = Mathf.Atan2(vLook.y, vLook.x) * Mathf.Rad2Deg;
        angle += 90.0f;

        gameObject.transform.rotation = Quaternion.AngleAxis(angle + 90.0f, Vector3.forward);
    }

    public void DestroyThis()
    {
        GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile[Calculate.GetMyTileIdx(transform.position)].GetComponent<Tile>().m_iOption = (int)m_PrevOption;
        Destroy(gameObject);
    }
}
